import type { PaginationProps } from '@pureadmin/table'
import { ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, toRefs } from 'vue'
// import { delConfig, getConfig, listConfig } from "@/api/system/config";
import { allocatedUserList, authUserCancel, authUserCancelAll } from '@/api/system/role'
import DictTag from '@/components/dict-tag/index.vue'
import { formatDate } from '@/utils/common'
import { useDicts } from '@/utils/dict'
import { message } from '@/utils/message'
import { useRoute, useRouter } from 'vue-router'

export function useConfig() {
  const route = useRoute()
  const router = useRouter()
  const data = reactive({
    form: {},
    queryParams: {
      roleId: route.params.roleId,
      userName: undefined,
      phonenumber: undefined,
    },
  })
  const { form, queryParams } = toRefs(data)
  const formDialogVisible = ref(false)

  const roleId = ref(route.params.roleId)
  const title = ref('')
  const userIds = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const showSelection = true

  const dataList = ref([])
  const loading = ref(true)

  const { sys_normal_disable } = useDicts('sys_normal_disable')
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  })
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: 55,
      align: 'left',
      hide: ({ checkList }) => !checkList.includes('勾选列'),
    },
    {
      label: '序号',
      type: 'index',
      width: 70,
      hide: ({ checkList }) => !checkList.includes('序号列'),
    },
    {
      label: '用户名称',
      prop: 'userName',
      minWidth: 100,
    },
    {
      label: '用户昵称',
      prop: 'nickName',
      minWidth: 150,
    },
    {
      label: '邮箱',
      prop: 'email',
      minWidth: 150,
    },
    {
      label: '手机',
      prop: 'phonenumber',
      minWidth: 100,
    },
    {
      label: '状态',
      prop: 'status',
      minWidth: 120,
      cellRenderer: (scope) => {
        return <DictTag options={sys_normal_disable} value={scope.row.status} />
      },
    },
    {
      label: '创建时间',
      minWidth: 180,
      prop: 'createTime',
      formatter: ({ createTime }) => formatDate(createTime),
    },
    {
      label: '操作',
      fixed: 'right',
      width: 180,
      slot: 'operation',
    },
  ]

  /** 查询列表 */
  async function onSearch() {
    loading.value = true
    const params = {
      ...queryParams.value,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
    const { rows, total } = await allocatedUserList(params)
    dataList.value = rows
    pagination.total = total
    loading.value = false
  }

  /**返回按钮 */
  function onClose() {
    router.push({ path: '/role' })
  }

  /** 重置查询 */
  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    onSearch()
  }

  /** 改变多选项 */
  function handleSelectionChange(selection) {
    userIds.value = selection.map((item) => item.configId)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 打开授权用户表弹窗 */
  function openSelectUser() {
    formDialogVisible.value = true
    title.value = '选择用户'
  }

  /** 取消授权按钮操作 */
  function cancelAuthUser(row) {
    ElMessageBox.confirm('确认要取消该用户"' + row.userName + '"角色吗？')
      .then(function () {
        return authUserCancel({
          userId: row.userId,
          roleId: queryParams.value.roleId,
        })
      })
      .then(() => {
        onSearch()
        message('取消授权成功', { type: 'success' })
      })
  }

  /** 批量取消授权按钮操作 */
  function cancelAuthUserAll() {
    const roleId = queryParams.value.roleId
    const uIds = userIds.value.join(',')
    ElMessageBox.confirm('是否取消选中用户授权数据项?')
      .then(function () {
        return authUserCancelAll({ roleId: roleId, userIds: uIds })
      })
      .then(() => {
        onSearch()
        message('取消授权成功', { type: 'success' })
      })
  }

  /** 改变分页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  /** 改变当前分页 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  onMounted(() => {
    onSearch()
  })

  return {
    roleId,
    form,
    title,
    loading,
    columns,
    multiple,
    dataList,
    pagination,
    queryParams,
    showSelection,
    formDialogVisible,
    onClose,
    onSearch,
    resetForm,
    openSelectUser,
    cancelAuthUser,
    cancelAuthUserAll,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
  }
}
